const dayjs = require('dayjs');
const { Controller } = require('varal');
const Weapp = require('../libs/weapp');

class OrderController extends Controller {
	async index() {
		const { page = 1, page_size = 20, out_trade_no, contact, phone, company, uscc, category_id, work_id, is_cart, is_draft, order_time,
			car_name,
			status,
			pay_status,
			tree_parent_fullname,
			team_parent_fullname,
			agency_fullname
		} = this.app.fields;

		let [order_start_time, order_end_time] = JSON.parse(order_time || '[]');

		const serv = this.app.service('OrderService');
		return serv.get({
			out_trade_no, contact, phone, company, uscc, category_id, work_id,
			order_start_time,
			order_end_time,

			//购物车，代客下单订单默认不展示
			is_cart, is_draft,

			car_name,
			status,
			pay_status,
			tree_parent_fullname,
			team_parent_fullname,
			agency_fullname
		}, page, page_size).then(({ data, total }) => {
			this.app.json({
				err_code: 0,
				data: {
					data,
					total
				}
			})
		})
	}

	async info() {
		const { id } = this.app.fields;
		const serv = this.app.service('OrderService');

		const data = await serv.info({ id });

		this.app.json({
			err_code: 0,
			data
		})
	}

	async delete() {
		const { id } = this.app.fields;

		const serv = this.app.service('OrderService');

		return serv.delete(id).then(() => {
			this.app.json({
				err_code: 0
			})
		})
	}

	async save() {
		const params = this.app.fields;
		const serv = this.app.service('OrderService');

		return serv.save(params).then(async () => {
			if (params.out_trade_no) {
				await this.app.service('JournalService').dispatch(params.out_trade_no);
			}

			this.app.json({
				err_code: 0
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		});

	}

	async certificateUrl() {
		const { id } = this.app.fields;

		const weapp = new Weapp();
		//默认有效期2天
		const { url_link } = await weapp.urlscheme('pages/member/order/upload', `id=${id}`, 172800);

		this.app.json({
			err_code: 0,
			data: {
				url: url_link
			}
		})
	}
}

exports = module.exports = OrderController;
